package com.caizi.classload;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;

public class CryptoClassLoader extends ClassLoader {
    int key;

    public CryptoClassLoader(int key) {
        this.key = key;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        byte[] classBytes = null;
        try {
            classBytes = loadClassBytes(name);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Class<?> c1 = defineClass(name, classBytes, 0, classBytes.length);
        if (c1 == null) {
            throw new ClassNotFoundException();
        }
        return c1;
    }

    private byte[] loadClassBytes(String name) throws Exception {
        String cname = name.replace('.', '/') + ".caesar";
        FileInputStream in = null;
        ByteArrayOutputStream buffer = null;
        try {
            in = new FileInputStream(cname);
            buffer = new ByteArrayOutputStream();

            int ch;
            while ((ch = in.read()) != -1) {
                byte b = (byte) (ch - key);
                buffer.write(b);
            }
            return buffer.toByteArray();
        } finally {
            if (in != null) {
                in.close();
            }
            if (buffer != null) {
                buffer.close();
            }
        }
    }
}
